package cn.rocksolid.proxy.restful.sys;

import cn.rocksolid.sport.common.error.RSE;
import cn.rocksolid.sport.common.http.R;
import cn.rocksolid.sport.common.http.utils.HttpUtils;
import cn.rocksolid.sport.common.utils.AssertUtils;
import cn.rocksolid.sport.security.entity.RoleEntity;
import cn.rocksolid.sport.security.service.RoleService;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

/**
 * System role service
 *
 * @author Axl Zhao
 * @email axl.zhao@163.com
 */
@RestController
@RequestMapping("/sys/role")
public class RoleController {

  private final RoleService roleService;

  @Autowired
  public RoleController(final RoleService roleService) {
    this.roleService = roleService;
  }

  /**
   * Pagination of roles
   */
  @PostMapping("/page")
  @RequiresPermissions("sys:role:info")
  public Object page(@RequestBody final JSONObject cond) {
    return roleService.paging(HttpUtils.resolve(), cond);
  }

  /**
   * Get
   */
  @GetMapping("/{id}")
  @RequiresPermissions("sys:role:info")
  public Object get(@PathVariable("id") String id) {
    return roleService.get(id);
  }

  /**
   * Create
   */
  @PutMapping
  @RequiresPermissions("sys:role:create")
  public Object create(@RequestBody RoleEntity role) {
    validate(role);
    roleService.create(role);
    return R.ok();
  }

  /**
   * Modify
   */
  @PostMapping
  @RequiresPermissions("sys:role:modify")
  public Object modify(@RequestBody RoleEntity role) {
    validate(role);
    roleService.modify(role);
    return R.ok();
  }

  /**
   * Remove
   */
  @DeleteMapping
  @RequiresPermissions("sys:role:remove")
  public R remove(@RequestBody Collection<String> roleIds) {
    roleService.removes(roleIds);
    return R.ok();
  }

  /**
   * Validate
   */
  private void validate(RoleEntity role) {
    AssertUtils.isNotNull(role, RSE.INVALID_PAYLOAD);
    AssertUtils.isName(role.getTitle(), RSE.INVALID_RNAME);
    // AssertUtils.isTrue(sysRoleService.countSysRoles(role) == 0, RSE.DUP_RNAME);
  }
}
